package com.javalaoniu.tool.utils;

import com.javalaoniu.tool.exception.MyAppRunException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

/**
 * 对象赋值工具类
 *
 * @author liangxn
 */
public class BeanCopyUtil {

    private static final Logger logger = LoggerFactory.getLogger(BeanCopyUtil.class);

    /**
     * 相同对象合并，将原对象的非空属性的值赋值给目标对象
     *
     * @param origin      源对象
     * @param destination 目标对象
     * @param <T>         对象的类型
     */
    public static <T> void merge(T origin, T destination) {
        if (origin == null || destination == null) {
            return;
        }
        if (!origin.getClass().equals(destination.getClass())) {
            return;
        }

        Field[] fields = origin.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object value = field.get(origin);
                if (null != value) {
                    field.set(destination, value);
                }
            } catch (IllegalAccessException e) {
                logger.error("访问对象异常", e);
                throw new MyAppRunException("访问对象异常");
            }
            field.setAccessible(false);
        }
    }
}